package com.zy.mobile.message.push.netty.chapter8;

import com.zy.mobile.message.push.netty.chapter8.protobuf.SubscribeReqProto;
import com.zy.mobile.message.push.netty.chapter8.protobuf.SubscribeReqProto.SubscribeReq;
import com.zy.mobile.message.push.netty.chapter8.protobuf.SubscribeRespProto;
import com.zy.mobile.message.push.netty.chapter8.protobuf.SubscribeRespProto.SubscribeResp;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

@Sharable
public class SubReqServerHandler extends ChannelHandlerAdapter{
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		// TODO Auto-generated method stub
		SubscribeReqProto.SubscribeReq req = (SubscribeReq) msg;
		if("zhangyi".equalsIgnoreCase(req.getUserName())){
			System.out.println("Service accept client subscribe req : ["+req.toString()+"]");
			ctx.writeAndFlush(resp(req.getSubReqId()));
		}
	}
	
	private SubscribeRespProto.SubscribeResp resp(int subReqId){
		SubscribeRespProto.SubscribeResp.Builder builder = SubscribeRespProto.SubscribeResp.newBuilder();
		builder.setSubReqId(subReqId);
		builder.setRespCode(0);
		builder.setDesc("Netty book order succeed, 3 day later, sent to the designated address");
		return builder.build();	
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		// TODO Auto-generated method stub
		cause.printStackTrace();
		ctx.close();
	}
}
